#!usr/bin/env python
# conding = utf-8

import os

from google.appengine.ext.webapp import template
from google.appengine.ext import db
from model.model import Member
from google.appengine.api import memcache
from config import ONE_MONTH

def WriteJson(request,data,temp):
    path = os.path.join(os.path.dirname(os.path.dirname(__file__)),'static','api',temp)
    request.response.headers['Content-type'] = "application/json"
    output = template.render(path,data)
    request.response.out.write(output)
    
def get_current_item(member):
    item = memcache.get("PassByItem::"+str(member.key().id))
    if item:
        return item
    items = db.GqlQuery('SELECT * FROM PassbyItem WHERE member = :1', member)
    if items.count()>0:
        item = items[0]
        memcache.add("PassByItem::"+str(member.key().id), item, ONE_MONTH)
        return item
    return None

class AppKey(db.Model):
    app_key = db.StringProperty(required=True)
    app_secret = db.StringProperty()
    app_name = db.StringProperty()
    app_owner = db.ReferenceProperty(Member)
    app_description = db.TextProperty()
    has_checked = db.BooleanProperty()
    
    def verify_app_key(appkey):
        one =  memcache.get('AppKey::' + str(appkey))
        if one:
            return one
        q = db.GqlQuery('SELECT * FROM AppKey WHERE app_key = :1', appkey)
        if q.count() == 1 and q[0].has_checked:
            memcache.add('AppKey::' + str(appkey), q[0], 15 * 365)
            return q[0]
        return False
    verify_app_key = staticmethod(verify_app_key)
    
class AccessToken(db.Model):
    access_token_key = db.StringProperty(required=True)
    access_token_secret = db.StringProperty(required=True)
    token_owner = db.ReferenceProperty(Member,required=True)
    
    def to_string(self):
        return self.access_token_key
    
    def __str__(self):
        return self.to_string()
    
    def verify_access_token(access_key):
        one =  memcache.get('AccessToken::' + str(access_key))
        if one:
            return one
        q = db.GqlQuery('SELECT * FROM AccessToken WHERE access_token_key = :1', access_key)
        if q.count() == 1:
            memcache.add('AccessToken::' + str(access_key), q[0], 15 * 365)
            return q[0]
        return False
    verify_access_token = staticmethod(verify_access_token)